//
//  ResponseParser.m
//  protesteya
//
//  Created by Sebastian Bene on 9/24/13.
//  Copyright (c) 2013 Obligatorio Dispositivos Moviles. All rights reserved.
//

#import "ResponseParser.h"
#import "DataAccess.h"

@implementation ResponseParser

-(TwitterBaseResponse *) ParseTwitterBaseResponse:(NSDictionary *)twitterResponse
{
    TwitterBaseResponse *result = [[TwitterBaseResponse alloc] init];
    
    NSString *errorMessage = [self ResponseHasErrors:twitterResponse];
    
    if(errorMessage)
    {
        result.responseType = TwitterResponseError;
        result.errorMessage = errorMessage;
    }
    else
    {
        result.responseType = TwitterResponseOk;
    }
    
    return result;
}

-(GetTweetResponse *)ParseGetTweetResponse:(NSDictionary *)twitterResponse withImage:(BOOL)withImage
{
    GetTweetResponse *result = [[GetTweetResponse alloc] init];
    
    NSString *errorMessage = [self ResponseHasErrors:twitterResponse];
    
    if(errorMessage)
    {
        result.responseType = TwitterResponseError;
        result.errorMessage = errorMessage;
    }
    else
    {
        result.tweet = twitterResponse;
        result.responseType = TwitterResponseOk;
        
        result.tweetId = [twitterResponse[@"id"] stringValue];
                
        NSDictionary *coordinates = twitterResponse[@"coordinates"];
        
        if(![coordinates isKindOfClass:[NSNull class]])
        {
            result.latitude = coordinates[@"coordinates"][1];
            result.longitude = coordinates[@"coordinates"][0];
        }
        
        NSDictionary *user = twitterResponse[@"user"];

        result.userName = user[@"name"];
        
        result.createdDate = [twitterResponse[@"created_at"] substringToIndex:16];
        
        if(withImage == YES)
        {
            result.image = [self GetImage:twitterResponse[@"entities"][@"media"][0][@"media_url"]];
            result.userImage = [self GetImage:user[@"profile_image_url"]];
        }
        
        result.text = [self GetTweetText:twitterResponse[@"text"] withImageUrl:twitterResponse[@"entities"][@"media"][0][@"url"]];
        
        DataAccess *dataAccess = [[DataAccess alloc] init];
        Tweet *storeTweet = [dataAccess GetTweet:result.tweetId];
        
        if(storeTweet)
        {
            result.isFavorite = storeTweet.favorite.boolValue;
            result.isRetweeted = storeTweet.retweeted.boolValue;
        }
        else
        {
            result.isFavorite = NO;
            result.isRetweeted = NO;
        }
    }
    
    return result;
}

-(GetTweetsListResponse *) ParseGetTweetsListResponse:(NSDictionary *) twitterResponse
{
    GetTweetsListResponse *result = [[GetTweetsListResponse alloc] init];

    NSString *errorMessage = [self ResponseHasErrors:twitterResponse];
    
    if(errorMessage)
    {
        result.responseType = TwitterResponseError;
        result.errorMessage = errorMessage;
    }
    else
    {
        result.responseType = TwitterResponseOk;        
        result.tweetsList = twitterResponse[@"statuses"];
        if ([result.tweetsList count] == 0)
        {
            NSArray *errors = twitterResponse[@"errors"];
            if ([errors count])
            {
                result.searchState = TwitterSearchStateFailed;
            }
            else
            {
                result.searchState = TwitterSearchStateNotFound;
            }
        }
        else
        {
            NSMutableArray *retweetsAndComments = [[NSMutableArray alloc] init];
            for(NSDictionary *tweet in result.tweetsList)
            {
                if(tweet[@"in_reply_to_status_id_str"] != (id)[NSNull null] || tweet[@"retweeted_status"] != nil)
                {
                    [retweetsAndComments addObject:tweet];
                }
                else
                {
                    [tweet setValue:[self GetTweetText:tweet[@"text"] withImageUrl:nil] forKey:@"text"];
                }
            }
            
            [result.tweetsList removeObjectsInArray:retweetsAndComments];
        }
    }
    
    return result;
}

-(TwitterBaseResponse *) ParseCommentsListResponse:(NSDictionary *)twitterResponse inReplyTo:(NSString *)inReplyTo
{
    NSString *errorMessage = [self ResponseHasErrors:twitterResponse];
    
    if(errorMessage)
    {
        TwitterBaseResponse* result = [[TwitterBaseResponse alloc] init];
        result.responseType = TwitterResponseError;
        result.errorMessage = errorMessage;
        
        return result;
    }
    else if (twitterResponse[@"statuses"])
    {
        GetTweetsListResponse *result = [[GetTweetsListResponse alloc] init];
        
        result.responseType = TwitterResponseOk;
        result.tweetsList = [[NSMutableArray alloc]init];;
        
        for (NSDictionary *tweet in twitterResponse[@"statuses"]) {
            NSString* tweetInReplyTo = tweet[@"in_reply_to_status_id_str"];
            if (tweetInReplyTo != (id)[NSNull null] && tweetInReplyTo.length != 0 && [tweetInReplyTo isEqualToString:inReplyTo])
            {
                [result.tweetsList addObject:tweet];
            }
        }
        
        if ([result.tweetsList count] == 0)
        {
            NSArray *errors = twitterResponse[@"errors"];
            if ([errors count])
            {
                result.searchState = TwitterSearchStateFailed;
            }
            else
            {
                result.searchState = TwitterSearchStateNotFound;
            }
        }
        else
        {
            for(NSDictionary *tweet in result.tweetsList)
            {
                [tweet setValue:[self GetTweetText:tweet[@"text"] withImageUrl:nil] forKey:@"text"];
            }
        }
        
        return result;
        
    } else {
        return [self ParseGetTweetResponse:twitterResponse withImage:false];
    }
}

-(NSString *) ResponseHasErrors:(NSDictionary *)response
{
    NSString *result = nil;
    if(response)
    {
        if([response[@"errors"] isKindOfClass:[NSString class]])
        {
            result = response[@"errors"];
        }
        else
        {
            result = response[@"errors"][0][@"message"];
        }
    }
    else
    {
        result = @"Twitter response is Nil";
    }
    
    return result;
}

-(NSString *) GetTweetText:(NSString *)tweetText withImageUrl:(NSString *)imageUrl
{
    NSString *result;
    result = [tweetText stringByReplacingOccurrencesOfString:HASHTAG withString:@""];
    
    if(imageUrl)
    {
        result = [tweetText stringByReplacingOccurrencesOfString:imageUrl withString:@""];
    }
    
    result = [result stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    return result;
}

-(UIImage *) GetTweetImage:(NSDictionary *)tweet
{
    return [self GetImage:tweet[@"entities"][@"media"][0][@"url"]];
}

-(UIImage *) GetImage:(NSString *)imageUrl
{   
    if(imageUrl)
    {
        NSURL *url = [NSURL URLWithString:imageUrl];
        NSData *imageData = [[NSData alloc] initWithContentsOfURL:url];
        return [UIImage imageWithData:imageData];
    }
    else
    {
        return nil;
    }
}

@end
